#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import re
from datetime import datetime, timedelta
from my_app.create_photo import constant
from dateutil.relativedelta import relativedelta


class CalculateTime:

    def __init__(self, t: int):
        self.t = t
        self.date_format = "%Y-%m-%d"
        self._now = datetime.now()  # 当前时间
        self.start_time = (self._now + timedelta(days=t))  # 开始时间  T+n天

    def year_last_day(self, year: int):
        """计算T+n xx年龄的最后一天"""
        y = (self.start_time - relativedelta(years=year+1))
        d = (y + timedelta(days=1)).strftime(self.date_format)
        return str(d)

    def year_first_day(self, year: int):
        """计算T+n xx年龄的第一天"""
        y = (self.start_time - relativedelta(years=year)).strftime(self.date_format)
        return str(y)

    def n_days_ago(self, day: int):
        """xx天之前的日期"""
        d = (self.start_time - timedelta(days=day)).strftime(self.date_format)
        return str(d)

    def now(self):
        """当前时间"""
        return self._now.strftime(self.date_format)

    def n_after_year(self, year, start_year: str = ''):
        """n年后"""
        if start_year == '':
            y = (self.start_time + relativedelta(years=year)).strftime("%Y-%m-%d %H:%M:%S")
        else:
            y = (datetime.strptime(start_year, "%Y-%m-%d %H:%M:%S") + relativedelta(years=year)).strftime("%Y-%m-%d %H:%M:%S")
        return str(y)


class IdNumber(str):

    def __init__(self, id_number):
        super(IdNumber, self).__init__()
        self.id = id_number
        self.area_id = int(self.id[0:6])
        self.birth_year = int(self.id[6:10])
        self.birth_month = int(self.id[10:12])
        self.birth_day = int(self.id[12:14])

    def get_area_name(self):
        """根据区域编号取出区域名称"""
        return constant.AREA_INFO[self.area_id]

    def get_birthday(self):
        """通过身份证号获取出生日期"""
        return "{0}-{1}-{2}".format(self.birth_year, self.birth_month, self.birth_day)

    def get_age(self):
        """通过身份证号获取年龄"""
        now = (datetime.now() + timedelta(days=1))
        year, month, day = now.year, now.month, now.day

        if year == self.birth_year:
            return 0
        else:
            if self.birth_month > month or (self.birth_month == month and self.birth_day > day):
                return year - self.birth_year - 1
            else:
                return year - self.birth_year

    def get_sex(self):
        """通过身份证号获取性别， 女生：0，男生：1"""
        return int(self.id[16:17]) % 2

    def get_check_digit(self):
        """通过身份证号获取校验码"""
        check_sum = 0
        for i in range(0, 17):
            check_sum += ((1 << (17 - i)) % 11) * int(self.id[i])
        check_digit = (12 - (check_sum % 11)) % 11
        return check_digit if check_digit < 10 else 'X'

    @classmethod
    def verify_id(cls, id_number):
        """校验身份证是否正确"""
        if re.match(constant.ID_NUMBER_18_REGEX, id_number):
            check_digit = cls(id_number).get_check_digit()
            return str(check_digit) == id_number[-1]
        else:
            return bool(re.match(constant.ID_NUMBER_15_REGEX, id_number))

    @classmethod
    def generate_id(cls, sex=0, birthday_num="20050824", area=''):
        """生成身份证号，sex = 0表示女性，sex = 1表示男性"""
        # 区域码(6位数)
        if area == '':
            id_number = str(random.choice(list(constant.AREA_INFO.keys())))
        else:
            id_number = str(area)
        # 出生日期(8位数)
        id_number += str(birthday_num)
        # 顺序码(2位数)
        id_number += str(random.randint(10, 99))
        # 性别码(1位数)
        id_number += str(random.randrange(sex, 10, step=2))
        # 校验码(1位数)
        return id_number + str(cls(id_number).get_check_digit())


if __name__ == '__main__':
    id_n = IdNumber.generate_id(sex=1)  # 生成身份证号
    print(id_n)
    # print(IdNumber(id_n).area_id)  # 地址编码:410326
    print(IdNumber(id_n).get_area_name())  # 地址:河南省洛阳市汝阳县
    print(IdNumber(id_n).get_birthday().split("-"))  # 生日:1995-7-10
    # print(IdNumber(id_n).get_age())  # 年龄:(岁)
    print(IdNumber(id_n).get_sex())  # 性别:1(男)
    # print(IdNumber(id_n).get_check_digit())  # 校验码:7
    # print(IdNumber.verify_id(id_n))  # 检验身份证是否正确
    print(CalculateTime(t=0).n_after_year(year=10, start_year="2002-09-20 00:00:00"))


